<template>
  <view style="position: relative;" class="flex-col justify-center align-center">
    <!-- 显示 GIF 图片 -->
    <image
      :src="gifUrl"
      mode="aspectFit"
	  :style="{ width: imageWidth + 'px', height: imageHeight + 'px' }"
      @tap="onImageTap"
	  @load="onImageLoad"
	  class="gif-img"
    ></image>

    <!-- 可拖拽的文字层 -->
    <movable-area
      style="position: absolute; top: 0; margin: 10px;"
      :style="{ width: imageWidth + 'px', height: imageHeight + 'px' }"
    >
      <movable-view
        :x="textX"
        :y="textY"
        direction="all"
        @change="onDrag"
        :style="{
          position: 'absolute',
          padding: '5px',
          borderRadius: '5px',
          fontSize: fontSize + 'px',
          fontFamily: fontStyles[fontStyleIndex].key,
          color: fontColor,
          writingMode: textOrientation === 'vertical' ? 'vertical-rl' : 'horizontal-tb',
          display: 'flex',
          flexDirection: textOrientation === 'vertical' ? 'column' : 'row',
          alignItems: 'center',
          justifyContent: 'center',
		  width: textOrientation === 'vertical' ? 'min-content' : 'max-content' 
        }"
      >
        {{ text }}
      </movable-view>
    </movable-area>

    <!-- 文字输入框 -->
    <view class="item_row flex-row justify-center align-center">
		<text class="text">输入文字：</text>
		<view class="flex-1">
			<input v-model="text" placeholder="输入文字" />
		</view>
	</view>

    <!-- 字体大小调整 -->
    <view class="item_row flex-row justify-center align-center">
      <text class="text">字体大小：</text>
	  <view class="flex-1">
		<slider :value="fontSize" min="10" max="50" @change="onFontSizeChange" />
	  </view>
    </view>

    <!-- 字体样式选择 -->
	<view class="item_row flex-row justify-center align-center">
	  <text class="text">字体样式：</text>
	  <view class="flex-1">
		<picker :value="fontStyleIndex" :range="fontStyles" @change="onFontStyleChange" range-key="value">
		  <view>{{ fontStyles[fontStyleIndex].value }}</view>
		</picker>
	  </view>
	</view>

    <!-- 字体颜色选择 -->
    <view class="item_row flex-row justify-center align-center">
      <text class="text">字体颜色：</text>
	  <view class="flex-1 flex-row justify-start">
		  <uv-pick-color ref="pickerColor" :color="color" @confirm="confirm"></uv-pick-color>
		  <uv-button @click="openColor" text="选择颜色"></uv-button>
	  </view>
    </view>

    <!-- 文字方向切换 -->
 <!--   <view class="item_row">
      <text>文字方向：</text>
      <button @click="toggleTextOrientation">
        {{ textOrientation === 'horizontal' ? '竖向显示' : '横向显示' }}
      </button>
    </view> -->
	
	<view class="item_row justify-center align-center">
		<text class="text">预览：</text>
		<view class="flex-1">
			<image
			  v-if="memeUrl.length > 0"
			  :src="memeUrl"
			  mode="aspectFit"
			  :style="{ width: (imageWidth / 2) + 'px', height: (imageHeight / 2) + 'px' }"
			  class="gif-img"
			></image>
		</view>
	</view>

    <!-- 生成按钮 -->
	<view class="item_row flex-row justify-center align-center" style="gap: 10rpx;">
		<uv-button type="success" text="制作" @click="generateMeme"></uv-button>
		
		<Adver ref="saveAdverRef" @adCompleted="downMeme">
			<uv-button 
				type="warning" 
				text="下载"
				@click="() => $refs.saveAdverRef.showRewardAd()" 
				v-show="isShowMote"
			 >
			</uv-button>
		</Adver>
		<!-- <uv-button type="warning" text="下载" @click="downMeme"></uv-button> -->
	</view>

    <!-- 显示生成的表情包 -->
    <!-- <uv-image v-if="memeUrl.length > 0" :src="memeUrl" mode="widthFix"></uv-image> -->
  </view>
</template>

<script>
import { memeGenerate } from '@/api/imgTools'
import { notAuthToast } from '@/hooks/common'
import { downImageByUrl } from '@/hooks/down'
import Adver from '@/framework/componentsUI/adver/index.vue'
export default {
  components: {
	Adver
  },
  data() {
    return {
      memeUrl: '',
      gifUrl: '', // GIF 图片地址
      text: '拖拽我', // 文字内容
      textX: 0, // 文字层 X 坐标
      textY: 0, // 文字层 Y 坐标
      imageWidth: 0, // 图片宽度
      imageHeight: 0, // 图片高度
      imageTop: 0, // 图片顶部位置
      imageLeft: 0, // 图片左侧位置
      fontSize: 24, // 字体大小
      fontStyles: [
		  { key: 'yuan', value: '圆字体' },
		  // { key: 'maokenZhuyuanTi', value: '猫啃珠圆体' },
		  { key: 'AlimamaFangYuanTiVF', value: '阿里妈妈方圆体' },
		  { key: 'PopGothicCjkTc-Bold', value: '大波浪圆体' },
		  // { key: 'BoTa', value: 'Potta One 波塔' },
		  // { key: 'id-ftmaru400', value: 'idfont手写粗圆 ' }
	  ],
      fontStyleIndex: 0, // 当前选中的字体样式索引
	  color: { r: 0, g: 0, b: 0, a: 0 },
      fontColor: '#000000', // 字体颜色
	  actualImageWidth: 0, // 图片实际宽度
	  actualImageHeight: 0, // 图片实际高度
      textOrientation: 'horizontal' // 文字方向：horizontal（横向）或 vertical（竖向）
    };
  },
  onLoad(options) {
    this.gifUrl = decodeURIComponent(options.imgUrl)
    this.getImageSize();
  },
  methods: {
    // 获取图片尺寸和位置
    getImageSize() {
      const query = uni.createSelectorQuery().in(this);
      query.select('image').boundingClientRect((rect) => {
        this.imageWidth = rect?.width || 1;
        this.imageHeight = rect?.height || 1;
        this.imageTop = rect?.top || 1;
        this.imageLeft = rect?.left || 1;
      }).exec();
    },
	// 图片加载完成事件
	onImageLoad(e) {
	  const { width, height } = e.detail;
	  this.actualImageWidth = width; // 图片实际宽度
	  this.actualImageHeight = height; // 图片实际高度
	  this.imageWidth = width
	  this.imageHeight = height
	},
    // 图片点击事件
    onImageTap(e) {
      const { x, y } = e.detail; // 获取点击位置相对于图片的坐标
      this.textX = x - 50; // 调整文字位置（假设文字宽度为 100px）
      this.textY = y - 20; // 调整文字位置（假设文字高度为 40px）
	},
	// 拖拽事件
	onDrag(e) {
	  // 将相对坐标转换为绝对坐标
	  this.textX = (e.detail.x / this.imageWidth) * this.actualImageWidth;
	  this.textY = (e.detail.y / this.imageHeight) * this.actualImageHeight;
	},
    // 字体大小调整事件
    onFontSizeChange(e) {
      this.fontSize = e.detail.value;
    },
    // 字体样式选择事件
    onFontStyleChange(e) {
      this.fontStyleIndex = e.detail.value;
    },
	openColor() {
		this.$refs.pickerColor.open();
	},
	confirm(e) {
		this.fontColor = e.hex
	},
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1, // 最多选择 1 张图片
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
        success: (res) => {
          // 更新图片路径
          this.gifUrl = res.tempFilePaths[0];
          // 重新获取图片尺寸
          this.getImageSize();
        },
        fail: (err) => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    // 切换文字方向
    toggleTextOrientation() {
      this.textOrientation = this.textOrientation === 'horizontal' ? 'vertical' : 'horizontal';
    },
    // 生成表情包
    generateMeme() {
	  this.memeUrl = ''
      const submitObj = {
        gifUrl: this.gifUrl,
        text: this.text,
        textX: this.textX,
        textY: this.textY + 18,
        fontSize: this.fontSize,
        fontStyle: this.fontStyles[this.fontStyleIndex].key,
        fontColor: this.fontColor,
        textOrientation: this.textOrientation // 传递文字方向
      };
	  uni.showLoading({title: '制作中...',mask: true})
      memeGenerate(submitObj).then(res => {
        this.memeUrl = this.getMemeUrl(res.msg, true);
		uni.hideLoading();
		// this.downMeme(this.memeUrl)
      });
    },
    getMemeUrl(tempId, isDown = false) {
      const path = isDown ? 'down' : 'preview';
      return this.$config.replacehUrl(`imgStore/imageTool/${path}?tempId=${tempId}`, true);
    },
	async downMeme(url){
		if(url == null){
			url = this.memeUrl
		}
		if(url == null || url?.length === 0){
			return uni.showToast({
			  title: '请先点击制作表情',
			  icon: 'none'
			});
		}
		if(!this.$getToken()){
			return notAuthToast()
		}
		if(!url){
			url = this.downUrl
		}
		uni.showLoading({title: '正在下载...',mask: true})
		const downName = 'image_' + new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19) + '.gif';
		await downImageByUrl(url, downName).catch(e => {
			uni.hideLoading();
		})
		uni.hideLoading();
	},
  }
};
</script>


<style lang="scss" scoped>
.item_row{
	width: 100%;
	padding: 4px 10px;
	.text{
		padding: 0 10px;
	}
	uni-button,button{
		margin: unset !important;
	}
}
.gif-img{
	border-radius: 10px;
	border: 1px solid #999;
	margin: 10px;
}
</style>